<template>
	<view class="phone-login-container">
		<view class="title">{{ pageTitle }}</view>
		
		<view class="login-form">
			<view class="input-group">
				<input type="number" maxlength="11" v-model="phone" placeholder="请输入手机号" />
			</view>
			<view class="input-group code-group">
				<input type="number" maxlength="6" v-model="code" placeholder="请输入验证码" />
				<button class="code-btn" :disabled="isSendingCode" @click="sendCode">
					{{ isSendingCode ? `重新发送(${countdown}s)` : '获取验证码' }}
				</button>
			</view>
			<button class="login-btn" :disabled="!isFormValid" @click="handleSubmit">{{ submitBtnText }}</button>
		</view>
		
		<view class="back-link" @click="goBack">返回上一页</view>
	</view>
</template>

<script>
	import { userLoginByPhone, bindPhone, bindWechat, getRandomCode } from '@/api/user.js';
	
	export default {
		data() {
			return {
				phone: '',
				code: '',
				isSendingCode: false,
				countdown: 60,
				mode: 'login', // login、bind、change
				generatedCode: '', // 保存生成的验证码
				openid: '', // 微信绑定时使用
				userId: '' // 手机号绑定时使用
			}
		},
		computed: {
			isFormValid() {
				return this.phone.length === 11 && this.code.length === 6;
			},
			pageTitle() {
				if (this.mode === 'bind') return '绑定手机号';
				if (this.mode === 'change') return '更换手机号';
				return '手机号登录';
			},
			submitBtnText() {
				if (this.mode === 'bind' || this.mode === 'change') return '立即绑定';
				return '登录';
			}
		},
		onLoad(options) {
			// 获取操作模式: login、bind、change
			if (options.mode) {
				this.mode = options.mode;
			}
			
			// 获取用户ID或openid
			if (options.userId) {
				this.userId = options.userId;
			} else if (options.openid) {
				this.openid = options.openid;
			} else {
				const userInfo = uni.getStorageSync('userInfo');
				if (userInfo) {
					this.userId = userInfo.id;
				}
			}
		},
		methods: {
			// 发送验证码
			sendCode() {
				if(!/^1\d{10}$/.test(this.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none'
					});
					return;
				}
				
				this.isSendingCode = true;
				this.countdown = 60;
				
				// 生成随机验证码
				this.generatedCode = getRandomCode();
				console.log('生成的验证码:', this.generatedCode);
				
				// 模拟发送验证码，实际使用时会调用短信API
				uni.showToast({
					title: `验证码: ${this.generatedCode}`,
					icon: 'none',
					duration: 3000
				});
				
				// 倒计时
				const timer = setInterval(() => {
					this.countdown--;
					if(this.countdown <= 0) {
						clearInterval(timer);
						this.isSendingCode = false;
					}
				}, 1000);
			},
			
			// 提交表单
			async handleSubmit() {
				if(!this.isFormValid) {
					return;
				}
				
				// 验证码校验
				if(this.generatedCode && this.code !== this.generatedCode) {
					uni.showToast({
						title: '验证码错误',
						icon: 'none'
					});
					return;
				}
				
				uni.showLoading({
					title: this.mode === 'login' ? '登录中...' : '绑定中...'
				});
				
				try {
					let res;
					
					if (this.mode === 'login') {
						// 手机号登录
						res = await userLoginByPhone({
							phone: this.phone,
							code: this.code
						});
					} else if (this.mode === 'bind') {
						// 绑定手机号
						res = await bindPhone({
							userId: this.userId,
							phone: this.phone,
							code: this.code
						});
					} else if (this.mode === 'change') {
						// 更换手机号
						res = await bindPhone({
							userId: this.userId,
							phone: this.phone,
							code: this.code
						});
					}
					
					uni.hideLoading();
					
					if (res.code === 200) {
						let user;
						
						if (this.mode === 'login') {
							user = res.data;
						} else { // 绑定或更换手机号
							user = res.data.user;
						}
						
						// 保存/更新用户信息
						uni.setStorageSync('userInfo', user);
						
						uni.showToast({
							title: this.mode === 'login' ? '登录成功' : '绑定成功',
							icon: 'success'
						});
						
						// 返回上一页或首页
						setTimeout(() => {
							if (this.mode === 'login') {
								uni.navigateBack({
									delta: 2,
									fail: () => {
										uni.switchTab({
											url: '/pages/index/index'
										});
									}
								});
							} else {
								uni.navigateBack();
							}
						}, 1500);
					} else {
						uni.showToast({
							title: res.msg || '操作失败，请重试',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					});
					console.error('操作失败', error);
				}
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			}
		}
	}
</script>

<style lang="scss">
	.phone-login-container {
		padding: 80rpx 50rpx;
		
		.title {
			font-size: 40rpx;
			font-weight: bold;
			margin-bottom: 60rpx;
			text-align: center;
		}
		
		.login-form {
			.input-group {
				margin-bottom: 40rpx;
				border-bottom: 1px solid #eeeeee;
				padding-bottom: 20rpx;
				
				input {
					height: 80rpx;
					font-size: 32rpx;
				}
				
				&.code-group {
					display: flex;
					justify-content: space-between;
					
					input {
						flex: 1;
					}
					
					.code-btn {
						width: 220rpx;
						height: 70rpx;
						line-height: 70rpx;
						font-size: 26rpx;
						margin-left: 20rpx;
						background-color: #f0f0f0;
						color: #333333;
						padding: 0;
						
						&[disabled] {
							background-color: #f5f5f5;
							color: #999999;
						}
					}
				}
			}
			
			.login-btn {
				height: 90rpx;
				line-height: 90rpx;
				border-radius: 45rpx;
				font-size: 32rpx;
				background-color: #1aad19;
				color: #ffffff;
				margin-top: 60rpx;
				
				&[disabled] {
					background-color: #9ed99e;
				}
			}
		}
		
		.back-link {
			text-align: center;
			margin-top: 40rpx;
			font-size: 28rpx;
			color: #1aad19;
		}
	}
</style> 